package com.vf.core.controller;

import java.io.BufferedReader;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.vf.core.render.BootstrapValid;
import com.vf.core.render.RenderBean;
import com.vf.core.render.RenderLayuiBean;

public class BaseController extends Controller {
	
	@NotAction
	public void renderSuccess(String message) {
		RenderBean renderBean = new RenderBean();
		renderBean.setCode(200);
		renderBean.setMessage(message);
		renderJson(renderBean);
	}

	@NotAction
	public void renderSuccess(String message, Object data) {
		RenderBean renderBean = new RenderBean();
		renderBean.setCode(200);
		renderBean.setMessage(message);
		renderBean.setData(data);
		renderJson(renderBean);
	}
	
	@NotAction
	public void render_401() {
		RenderBean renderBean = new RenderBean();
		renderBean.setCode(401);
		renderBean.setMessage("回话过期！");
		renderJson(renderBean);
	}
	
	@NotAction
	public void renderError(String message) {
		RenderBean renderBean = new RenderBean();
		renderBean.setCode(500);
		renderBean.setMessage(message);
		renderJson(renderBean);
	}
	
	@NotAction
	public void render_403(String message) {
		RenderBean renderBean = new RenderBean();
		renderBean.setCode(403);
		renderBean.setMessage(message);
		renderJson(renderBean);
	}

	@NotAction
	public void renderValidSuccess() {
		BootstrapValid v = new BootstrapValid();
		v.setValid(true);
		renderJson(v);
	}

	@NotAction
	public void renderValidFail() {
		BootstrapValid v = new BootstrapValid();
		v.setValid(false);
		renderJson(v);
	}

	@NotAction
	public void renderLayuiPage(int code,Object data, String msg, int count) {
		RenderLayuiBean renderBean = new RenderLayuiBean();
		renderBean.setCode(code);
		renderBean.setData(data);
		renderBean.setMsg(msg);
		renderBean.setCount(count);
		renderJson(renderBean);
	}
	
	/**
	 * 取Request中的数据对象
	 * @param valueType
	 * @return
	 * @throws Exception 
	 */
	@NotAction
	protected <T> T getRequestObject(Class<T> valueType) throws Exception {
	    StringBuilder json = new StringBuilder();
	    BufferedReader reader = this.getRequest().getReader();
	    String line = null;
	    while((line = reader.readLine()) != null){
	        json.append(line);
	    }
	    reader.close();
	    
	    return JSONObject.parseObject(json.toString(), valueType);
	}


}
